﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography;
using System.Text;

public partial class Admin_AddUser : System.Web.UI.Page
{
    PermissionController permission = new PermissionController();
    UsersController users = new UsersController();
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
            ddlPermission.DataSource = permission.GetAll();
            ddlPermission.DataTextField = "name";
            ddlPermission.DataValueField = "permission_id";
            ddlPermission.DataBind();
            
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        Users u = new Users();
        u.Permission_id = Convert.ToInt32(ddlPermission.SelectedValue);
        u.Username = txtUsername.Text;
        u.Password = MD5Encrypt(txtPassword.Text);
        u.Address = txtAddress.Text;
        u.Email = txtEmail.Text;
        u.Phone = txtPhone.Text;
        u.Birthday = pareDate(txtBirthdays.Text);
        u.Province = txtProvince.Text;
        u.District = txtDistrict.Text;
        if(ddlStatus.SelectedIndex==0)
        {
            u.Status = true;
        }
        else
        {
            u.Status = false;
        }
        u.DateStart = DateTime.Now;
        if(users.Insert(u)>0)
        {
            Response.Write("<script>alert('Tạo mới người dùng thành công')</script>");
            Response.Redirect("User.aspx");
        }
        else
        {
            Response.Write("<script>alert('Tạo mới người dùng bị lỗi')</script>");
        }
    }
    public static DateTime pareDate(string date)
    {
        char[] splitchar = { '-' };
        string[] strArr = date.Split(splitchar);
        string year = strArr[0];
        string month = strArr[1];
        string day = strArr[2];
        return new DateTime(Convert.ToInt32(year),Convert.ToInt32(month),Convert.ToInt32(day));
    }
    public static string MD5Encrypt(string orgString)
    {
        MD5CryptoServiceProvider mdcsp = new MD5CryptoServiceProvider();
        byte[] b = System.Text.Encoding.UTF8.GetBytes(orgString);
        b = mdcsp.ComputeHash(b);
        StringBuilder s = new StringBuilder();
        foreach (byte by in b)
        {
            s.Append(by.ToString("x2").ToLower());
        }

        return s.ToString();
    }
}